﻿<%@ WebHandler Language="C#" Class="imgup" %>


using System;
using System.Web;
using System.Text;
using System.IO;
using System.Drawing;
using Models;
using System.Text.RegularExpressions;
using System.Linq;
public class imgup : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        context.Response.ContentEncoding = Encoding.UTF8;
        if (context.Request["REQUEST_METHOD"] == "OPTIONS")
        {
            context.Response.End();
        }
        SaveFile();
    }

    /// <summary>
    /// 文件保存操作
    /// </summary>
    /// <param name="basePath"></param>
    private void SaveFile(string basePath = "/Up/")
    {
        string _datePath = DateTime.Now.ToString("yyyyMMdd") + "/";
        basePath += _datePath;

        string serverPath = "~" + basePath;
        var name = string.Empty;
        serverPath = (serverPath.IndexOf("~") > -1) ? System.Web.HttpContext.Current.Server.MapPath(serverPath) :
        serverPath;
        HttpFileCollection files = System.Web.HttpContext.Current.Request.Files;

        if (!Directory.Exists(serverPath))
            Directory.CreateDirectory(serverPath);


        //var suffix = files[0].ContentType.Split('/');
        //var _suffix = suffix[1];
        var _temp = System.Web.HttpContext.Current.Request["name"];

        //Regex regex = new Regex(@"《(?<value>[\s|\S]*)》");
        ////作品名称
        //string insertValue = regex.Match(_temp).Result("$1");

        //if (!string.IsNullOrEmpty(_temp))
        //{
        //    name = _temp;
        //}
        //else
        //{
        Random rand = new Random(24 * (int)DateTime.Now.Ticks);
        var ranNumber = rand.Next();
        name = ranNumber + ".jpg";
        //}

        if (!string.IsNullOrEmpty(HttpContext.Current.Request["_name"]) && HttpContext.Current.Request["_name"] != "null")
            ranNumber = int.Parse(HttpContext.Current.Request["_name"]);


        string makeThumb = "";
        var _base64 = System.Web.HttpContext.Current.Request["_base64"];
        if (!string.IsNullOrEmpty(_base64))
        {
            makeThumb = Base64StrToImage(_base64, serverPath, ranNumber.ToString());
        }
        else
        {
            var full = serverPath + name;
            files[0].SaveAs(full);
        }

        if (string.IsNullOrEmpty(HttpContext.Current.Request["_name"]) || HttpContext.Current.Request["_name"] == "null")
        {
            Regex regex = new Regex(@"《(?<value>[\s|\S]*)》");
            //作品名称
            string insertValue = regex.Match(_temp).Result("$1");
            string _CSName = "《" + insertValue + "》";
            //string[] Arr = _temp.Substring(0, _temp.IndexOf("《")).Split(new char[] { '+' }, StringSplitOptions.RemoveEmptyEntries);
            string authorName = _temp.Substring(0, _temp.IndexOf("《"));

            //string authorName= Arr[0];
            //string authorIntroduce= "<span style=\"white-space:nowrap;\">"+Arr[1]+"</span>";
            string authorIntroduce = "";

            using (Entities mydb = new Entities())
            {

                var author = mydb.Author.FirstOrDefault(p => p.AName == authorName);
                if (author == null)
                {
                    author = new Author();
                    author.AName = authorName;
                    author.ATel = "1";
                    author.AImg = "|";
                    author.AIntroduce = authorIntroduce;
                    author.IsTop = false;
                    author.IsLock = false;
                    author.ATime = DateTime.Now;
                    mydb.Author.Add(author);
                    mydb.SaveChanges();
                }

                V_Works lx = new V_Works();
                lx.SCNmae = _CSName;
                lx.SCKeyWord = "";// this.txtKeyword.Text;
                lx.SCpareID = 1;
                lx.SSort = 1;
                lx.SCIMG = basePath + name;
                lx.Introduce = "<p style=\"text-align:center;\"><img src=\"" + basePath + name + "\" width=\"600\" height=\"445\" alt=\"\" /></p><p style=\"text-align:center;\">《" + insertValue + "》</p>";
                lx.SAuthorId = author.AID;
                lx.IsTop = false;
                lx.IsLock = false;
                lx.SClick = 0;

                var works = mydb.V_Works.FirstOrDefault(p => p.SCNmae == _CSName);
                if (works == null)
                    mydb.V_Works.Add(lx);

                mydb.SaveChanges();
            }
        }

        var _result = "{\"jsonrpc\" : \"2.0\", \"result\" : \"" + ranNumber + "\", \"id\" : \"" + basePath + name + "\"}";
        System.Web.HttpContext.Current.Response.Write(_result);
    }

    /// <summary>
    /// 将Base64字符串转换为图片并保存到本地
    /// </summary>
    /// <param name="base64Str">base64字符串</param>
    /// <param name="savePath">图片保存地址，如：/dis/Images/10000.png</param>
    /// <returns></returns>
    public static string Base64StrToImage(string base64Str, string serverPath, string name)
    {
        var ret = "";
        try
        {
            serverPath = serverPath.Replace("Up", "upload");

            if (!Directory.Exists(serverPath))
                Directory.CreateDirectory(serverPath);

            var base64 = base64Str;//System.Web.HttpContext.Current.Request["_base64"];
            base64 = base64.Replace("data:image/png;base64,", "").Replace("data:image/jgp;base64,", "").Replace("data:image/jpg;base64,", "").Replace("data:image/jpeg;base64,", "");//将base64头部信息替换
            byte[] bytes = Convert.FromBase64String(base64);
            MemoryStream memStream = new MemoryStream(bytes);
            Image mImage = Image.FromStream(memStream);

            Bitmap bp = new Bitmap(mImage);
            MemoryStream ms = new MemoryStream();

            bp.Save(serverPath + name + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
            ms.Close();
            bp.Dispose();
            ret = serverPath + name + ".jpg";
        }
        catch (Exception ex)
        {
            ret = "";
        }
        return ret;
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}